package com.wenwei.sharebox.activity;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;

import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.wenwei.sharebox.R;
import com.wenwei.sharebox.adapter.CommonShareAdapter;
import com.wenwei.sharebox.base.BaseActivity;
import com.wenwei.sharebox.base.Constant;
import com.wenwei.sharebox.bean.BaseGoodsBean;
import com.wenwei.sharebox.net.ApiManager;
import com.wenwei.sharebox.net.BaseSubscriber;

import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Administrator on 2017/7/7.
 * <p>
 * 共享购物/共享租用
 */
public class ShareCommonActivity extends BaseActivity {

    @Bind(R.id.base_title)
    TextView baseTitle;
    @Bind(R.id.share_common_recycler)
    XRecyclerView shareCommonRecycler;

    CommonShareAdapter mBuyAdapter;
    @Bind(R.id.group_search_clear)
    ImageButton groupSearchClear;
    @Bind(R.id.search_edit)
    EditText searchEdit;

    private int mType = -1;//商品类型 -1：all 0:租用 1：购买
    private boolean isSearch = false;
    private String searchKey = "";

    @Override
    public int setLayoutResourceId() {
        return R.layout.activity_common_share;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @Override
    protected void init() {
        super.init();
        mType = getIntent().getIntExtra("type",-1);
        if(mType == -1){
            baseTitle.setText("共享物品");
        }else if (mType == 0){
            baseTitle.setText("共享租用");
        }else if(mType == 1){
            baseTitle.setText("共享购买");
        }else if (mType == 3){
            baseTitle.setText(getIntent().getStringExtra("className"));
        }
    }

    @Override
    protected void initData() {
        super.initData();
        if(mType != -1 && mType !=3){
            //租用商品数据
            getShareGoods(1);
        }else if (mType == 3){
            getGoodsList(1);
        }
        //当type为-1，表示搜索all商品
    }

    @Override
    protected void initView() {
        super.initView();
        if(mType == -1){
            baseTitle.setText("共享物品");
        }else if (mType == 0){
            baseTitle.setText("共享租用");
        }else if(mType == 1){
            baseTitle.setText("共享购买");
        }else {
            baseTitle.setText("共享物品");
        }

        searchEdit.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
                searchKey = textView.getText().toString();
                getSearchGoods(textView.getText().toString(),1);
                return false;
            }
        });

        searchEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (charSequence.length() > 0) {
                    groupSearchClear.setVisibility(View.VISIBLE);
                } else {
                    groupSearchClear.setVisibility(View.INVISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        shareCommonRecycler.setLayoutManager(new LinearLayoutManager(mContext));
        shareCommonRecycler.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                currentPage = 1;
                shareCommonRecycler.setLoadingMoreEnabled(true);
                getRefreshData(1);
            }

            @Override
            public void onLoadMore() {

                if (currentPage < pageTotalCount) {
                    currentPage = currentPage + 1;
                    shareCommonRecycler.setLoadingMoreEnabled(true);
                    getRefreshData(2);
                } else {
                    shareCommonRecycler.setLoadingMoreEnabled(false);
                    shareCommonRecycler.loadMoreComplete();
                }
            }
        });
        mBuyAdapter = new CommonShareAdapter(new CommonShareAdapter.CallBack() {
            @Override
            public void onItemClick(int id) {
                Bundle bundle = new Bundle();
                bundle.putInt("goodsId",id);
                goActivity(mContext,GoodsDetailsActivity.class,bundle);
            }
        });
        shareCommonRecycler.setAdapter(mBuyAdapter);
    }


    private void getRefreshData(int type){
        if(!isSearch){
            if(mType != -1 && mType !=3){
                getShareGoods(type);
            }else if (mType == 3){
                getGoodsList(type);
            }
        }else{
            getSearchGoods(searchKey,type);
        }
    }


    @OnClick({R.id.base_back, R.id.group_search_clear})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.base_back:
                finish();
                break;
            case R.id.group_search_clear:
                searchEdit.getText().clear();
                break;
        }
    }

    private int currentPage = 1;//当前分页
    private int pageTotalCount;//分页总数
    private ArrayList<BaseGoodsBean.DataBean> mCommonList = new ArrayList<>();
    private BaseSubscriber<BaseGoodsBean> commonShareSub;

    //共享购物 or 共享租用
    private void getShareGoods(final int type) {
        commonShareSub = new BaseSubscriber<BaseGoodsBean>(mContext) {
            @Override
            public void onSuccess(BaseGoodsBean baseGoodsBeen) {
                pageTotalCount = baseGoodsBeen.getTotal_page();

                if(type == Constant.LOAD_TYPE_REFRESH){
                    mCommonList.clear();
                    mCommonList.addAll(baseGoodsBeen.getData());
                    mBuyAdapter.setGoodsData(mCommonList);
                    shareCommonRecycler.refreshComplete();
                }else{
                    mCommonList.addAll(baseGoodsBeen.getData());
                    mBuyAdapter.setGoodsData(mCommonList);
                    shareCommonRecycler.loadMoreComplete();
                }

                mBuyAdapter.notifyDataSetChanged();
            }
        };
        ApiManager.getInstance().getShareShopRents(commonShareSub,mType ,"",currentPage,10);
    }

    //搜索购物商品 or 共享商品
    BaseSubscriber<BaseGoodsBean> searchSubscriber;
    private void getSearchGoods(String key,final int type){
        searchSubscriber = new BaseSubscriber<BaseGoodsBean>(mContext) {
            @Override
            public void onSuccess(BaseGoodsBean baseGoodsBean) {
                pageTotalCount = baseGoodsBean.getTotal_page();


                if(type == Constant.LOAD_TYPE_REFRESH){
                    mCommonList.clear();
                    mCommonList.addAll(baseGoodsBean.getData());
                    mBuyAdapter.setGoodsData(mCommonList);
                    shareCommonRecycler.refreshComplete();
                }else{
                    mCommonList.addAll(baseGoodsBean.getData());
                    mBuyAdapter.setGoodsData(mCommonList);
                    shareCommonRecycler.loadMoreComplete();
                }

                mBuyAdapter.notifyDataSetChanged();

            }
        };
        ApiManager.getInstance().getShareShopRents(searchSubscriber,mType,key,currentPage,10);
    }

    //All商品列表
    BaseSubscriber<BaseGoodsBean> goodsListSubscriber;
    private void getGoodsList(final int type){
        goodsListSubscriber = new BaseSubscriber<BaseGoodsBean>(mContext) {
            @Override
            public void onSuccess(BaseGoodsBean baseGoodsBean) {
                pageTotalCount = baseGoodsBean.getTotal_page();

                if(type == Constant.LOAD_TYPE_REFRESH){
                    mCommonList.clear();
                    mCommonList.addAll(baseGoodsBean.getData());
                    mBuyAdapter.setGoodsData(mCommonList);
                    shareCommonRecycler.refreshComplete();
                }else{
                    mCommonList.addAll(baseGoodsBean.getData());
                    mBuyAdapter.setGoodsData(mCommonList);
                    shareCommonRecycler.loadMoreComplete();
                }

                mBuyAdapter.notifyDataSetChanged();
            }
        };
        ApiManager.getInstance().getGoodsList(goodsListSubscriber,getIntent().getIntExtra("classId",0),currentPage,10);
    }
}
